import BigJs from 'big.js'
import store from '@/store/index.js'
import {showModalDbError} from '@/utils/helper.js'


const adminHomeStatistics = uniCloud.importObject('admin-home-statistics',{
    customUI:true
}) //第一步导入云对象
const db = uniCloud.database()


export async  function getAllMerchantList(){
    return db.collection(`food-merchant-list`)
    .field(`store_name`)
    .orderBy(`create_date desc`)
    .get()
}

/**
 * 获取商户的钱包信息
 * @param {string} merchantId - 商户唯一ID
 */
export async function getMerchantWallet(merchantId){
    const walletData={
        freeze_amount:`0.00`,
        available_amount:`0.00`
    }
    try {
        const {result:{data}}=await db.collection(`food-merchant-list`)
        .where(`_id=='${merchantId}'`)
        .field(`merchant_money_amount`)
        .get()
        if(data.length!==0){
            // 将金额转成元显示
            const { freeze_amount,available_amount} = data[0]?.merchant_money_amount || {}
            walletData.freeze_amount = new BigJs(freeze_amount).div(100).toFixed(3).slice(0, -1)
            walletData.available_amount = new BigJs(available_amount).div(100).toFixed(3).slice(0, -1)
        }
    } catch (error) {
        console.error(`获取商户钱包异常，异常原因:${error}`)
    }
    store.commit(`user/changeUserWallet`,walletData)
    return walletData
}
/**
 * 获取商户的订单总览
 * @param {string} merchantId - 商户唯一ID
 */
export async function getMerchantOrderDashboard(merchantId){
    let serverData ={
        progress:0,
        success:0,
        error:0,
        total:0
    }
    try {
        const results = await  adminHomeStatistics.merchantOrderDashboard(merchantId)
        if(results.myErrCode!==0){
            return showModalDbError(results)
        }
        const {data} = results
        serverData= data
    } catch (error) {
        console.error(`获取头部商户的订单总览，异常原因:${error}`)
    }
    store.commit(`user/changeOrderDashboard`,serverData)
    return serverData
}
